package com.wyy.config;

import com.wyy.beans.Resource;
import com.wyy.beans.Role;
import com.wyy.beans.User;
import com.wyy.service.ResourceService;
import com.wyy.service.RoleService;
import com.wyy.service.UserService;
import com.wyy.util.RedisUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class MyRealm extends AuthorizingRealm {

    @Autowired
    private UserService userService;

    @Autowired
    private RoleService roleService;

    @Autowired
    private ResourceService resourceService;

    // 资源授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principal) {
        SimpleAuthorizationInfo authorization = new SimpleAuthorizationInfo();

        // 从认证中获取当前的信息
        User user = (User) principal.getPrimaryPrincipal();
        List<Role> roles = roleService.getRoleByUserId(user.getUid());

        // 从数据库查询当前用户的角色列表，并装载到资源授权器里
        roles.forEach(item -> {
            authorization.addRole(item.getRoleName());

            // 再去查询每个角色拥有的资源列表，并装载到资源授权器里
            List<Resource> resources = resourceService.getResourcesByRoleId(item.getRid());

            resources.forEach(it -> {
                authorization.addStringPermission(it.getResourceName());
            });
        });
        return authorization;
    }

    // 身份认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {

        String telephoneNumber = (String) token.getPrincipal();

        User newUser = userService.getUserByTelephoneNumber(telephoneNumber).getData();
        if (newUser == null) {
            throw new AccountException("This User Does Not Exist");
        }
        return new SimpleAuthenticationInfo(newUser, newUser.getPassword(), getName());
    }
}
